package com.hanhai.zrb.mobile.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hanhai.common.annotation.LoginNeedless;
import com.hanhai.zrb.api.biz.result.UserCenterResult;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.UserInfoService;
import com.hanhai.zrb.api.biz.service.UserRegisterCheckService;
import com.hanhai.zrb.api.biz.service.UserRegisterService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.biz.service.ValidateCodeSendService;
import com.hanhai.zrb.mobile.result.BaseApiResult;
import com.hanhai.zrb.mobile.service.LoginUserService;
import com.hanhai.zrb.model.common.ValidateCodeSend.BizTypeEnum;
import com.hanhai.zrb.model.common.ValidateCodeSend.SendSMSTypeEnum;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.enums.UserInfoName;
import com.hanhai.zrb.model.user.vo.UserInfoVO;
import com.hanhai.zrb.model.user.vo.UserRegisterVo;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;

/**       
 * 项目名称：mobile-api   
 * 类名称：RegisterApiController   
 * 类描述：APP注册接口
 * 创建人：pengbohai   
 * 创建时间：2015年6月17日 上午11:06:45   
 * 修改人：pengbohai   
 * 修改时间：2015年6月17日 上午11:06:45   
 * 修改备注：   
 * @Copyright: 2015 汉海集团有限公司 All rights reserved.
 * @version v2
 */
@LoginNeedless
@RequestMapping("/register")
@RestController
public class RegisterApiController {

	private static final Logger LOGGER = LoggerFactory.getLogger(RegisterApiController.class);

	@Resource
	private ValidateCodeSendService validateCodeSendService;
	
	@Resource
	private UserRegisterCheckService userRegisterCheckService;
	
	@Resource
	private LoginUserService loginUserService;
	
	@Resource
	private CityInfoService cityInfoService;
	
	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	private UserRegisterService userRegisterService;
	
	
	@Resource
	private UserService userService;
	
	private static String regpw = "^[^\\s]{6,16}$";
	
	private static String regMobile = "^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$";
	/** 
	 * @Title: checkMobileRegister 
	 * @Description: TODO(验证手机号是否被使用-是否已存在) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "验证手机号是否已经注册",  response = BaseApiResult.class, notes = "验证手机号")
	@RequestMapping(value="/checkMobileRegister")
	public BaseApiResult checkMobileRegister(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "mobile", value = "手机号")
			@RequestParam(value = "mobile", required = true)String mobile){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				UserCenterResult userCenterResult = userRegisterCheckService.checkMobileOrEmailExist(mobile, null);
				if (userCenterResult.isSuccess()) {
					result.setMsg("手机号未注册");
					return result;
				} 
				result.setMsg("手机号已注册");
				result.setRes(0);
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	
	/** 
	 * @Title: checkUnameRegister 
	 * @Description: TODO(单独验证用户名是否存) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "验证用户名是否已经注册",  response = BaseApiResult.class, notes = "验证用户名")
	@RequestMapping(value="/checkUnameRegister")
	public BaseApiResult checkUnameRegister(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "uname", value = "用户名")
			@RequestParam(value = "uname", required = true)String uname){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(uname)){
			boolean checkResult = userRegisterCheckService.checkUserNameExist(uname);
			if (checkResult) {
				result.setMsg("用户名可用");
				return result;
			}
			result.setMsg("用户名不可用或已注册");
			result.setRes(0);
		}else{
			result.setMsg("用户名不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	/** 
	 * @Title: saveAppUser 
	 * @Description: TODO(注册保存接口) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "保存用户注册信息",  response = BaseApiResult.class, notes = "保存信息")
	@RequestMapping(value="/saveAppUser")
	public BaseApiResult saveAppUser(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "uname", value = "用户名")String uname, 
			@ApiParam(required = true, name = "passWord", value = "密码")@RequestParam(value = "passWord", required = true)String passWord, 
			@ApiParam(required = true, name = "mobile", value = "手机号")@RequestParam(value = "mobile", required = true)String mobile, 
			@ApiParam(required = true, name = "smsCode", value = "短信验证码")@RequestParam(value = "smsCode", required = true)String smsCode){
		
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
			//	UserCenterResult checkResult = userRegisterService.checkSMSCode(mobile, smsCode, BizTypeEnum.SmsBindRegister);
				String identity = getMoblieRegisterExtraCodeIdentity(mobile);
				boolean checkResult = this.validateCodeSendService.checkExtralCacheCode(identity, smsCode);
				if(  checkResult){
					UserCenterResult userCenterResult = userRegisterCheckService.checkMobileOrEmailExist(mobile, null);
					UserRegisterVo registervo = new UserRegisterVo();
					if( userCenterResult.isSuccess()){
						if( passWord.trim().matches(regpw)){
							if( StringUtils.isNotBlank(uname)){
								boolean checkResult1 = userRegisterCheckService.checkUserNameExist(uname);
								if( checkResult1){
									registervo.setUname(uname);
									registervo.setPassword(passWord);
									registervo.setUmobile(mobile);
									/*registervo.setUserType(userType);
									registervo.setOrg(org);*/
									userRegisterService.doRegisterByMobile(registervo);
									User user = userService.findByUname(uname);
									
									/*UserCenterResult huaxinImRegiesterResult = userRegisterService.registerHuanxinImByUid(user.getUid());
									
									result.setMsg("注册成功");
									if(huaxinImRegiesterResult.isSuccess()){
										//TODO 记录日志，可能用户注册成功，im注册失败，这块还不成熟，处于实验阶段
									}else{
										LOGGER.error("regiester huanxinIm false userId={}",user.getUid());
									}*/
									
								}else{
									result.setMsg("用户名不可用");
									result.setRes(0);
								}
							}else{
								registervo.setPassword(passWord);
								registervo.setUmobile(mobile);
								/*registervo.setUserType(userType);
								registervo.setOrg(org);*/
								userRegisterService.doRegisterByMobile(registervo);
								result.setMsg("注册成功");
							}
						}else{
							result.setMsg("密码不符合规则");
							result.setRes(0);
						}
					}else{
						result.setMsg(userCenterResult.getMsg());
						result.setRes(0);
					}
				}else{
					result.setMsg("验证码过期，重新获取");
					result.setRes(0);
				}
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	private String getMoblieRegisterExtraCodeIdentity(String mobile){
		return "Mobile_Register_Extral_App_"+mobile;
	}
	
	/** 
	 * @Title: sendSMSRegister 
	 * @Description: TODO(注册短信校验码接口) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "注册短信发送",  response = BaseApiResult.class, notes = "注册短信发送")
	@RequestMapping(value="/sendSMSRegister")
	public BaseApiResult sendSMSRegister(HttpServletRequest request,HttpServletResponse response ,
			@ApiParam(required = true, name = "mobile", value = "手机号")
			@RequestParam(value = "mobile", required = true)String mobile){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				BizTypeEnum type  = BizTypeEnum.SmsBindRegister;
				int codeType = SendSMSTypeEnum.REGISTER.getIndex();
				UserCenterResult sendResult = userRegisterService.sendSMSCode(mobile, type.name(), type, codeType);
				if( sendResult.isSuccess()){
					result.setMsg("短信发送成功");
					return result;
				}
				result.setMsg(sendResult.getMsg());
				result.setRes(0);
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	/** 
	 * @Title: checkSMSRegisterCode 
	 * @Description: TODO(注册短信校验码接口) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "注册短信发送",  response = BaseApiResult.class, notes = "注册短信发送")
	@RequestMapping(value="/checkSMSRegister")
	public BaseApiResult checkSMSRegisterCode(HttpServletRequest request,HttpServletResponse response ,
			@ApiParam(required = true, name = "mobile", value = "手机号")
			@RequestParam(value = "mobile", required = true)String mobile,
			@ApiParam(required = true, name = "smsCode", value = "验证码")
			@RequestParam(value = "smsCode", required = true)String smsCode){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if(StringUtils.isNotBlank(smsCode)){
				BizTypeEnum type  = BizTypeEnum.SmsBindRegister;
				UserCenterResult checkResult = userRegisterService.checkSMSCode(mobile, smsCode, type);
				if( checkResult.isSuccess()){
					String identity = this.getMoblieRegisterExtraCodeIdentity(mobile);
					String extralCode = this.validateCodeSendService.createExtralCacheCode(identity);
					
					result.setMsg("验证成功");
					result.setData(extralCode);
					return result;
				}else{
					result.setMsg(checkResult.getMsg());
					result.setRes(0);
				}
			}else{
				result.setMsg("验证码不能为空");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	/** 
	 * @Title: sendSMSFindPW 
	 * @Description: TODO(找回密码校验码接口) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "找回密码短信发送",  response = BaseApiResult.class, notes = "找回密码短信发送")
	@RequestMapping(value="/sendSMSFindPW")
	public BaseApiResult sendSMSFindPW(HttpServletRequest request,HttpServletResponse response , 
			@ApiParam(required = true, name = "mobile", value = "手机号")
			@RequestParam(value = "mobile", required = true)String mobile){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				BizTypeEnum type  = BizTypeEnum.SmsFindPassword;
				int codeType = SendSMSTypeEnum.FIND_PASSWORD.getIndex();
				UserCenterResult sendResult = userRegisterService.sendSMSCode(mobile, type.name(), type, codeType);
				if( sendResult.isSuccess()){
					result.setMsg("短信发送成功");
					return result;
				}
				result.setMsg(sendResult.getMsg());
				result.setRes(0);
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	/** 
	 * @Title: changePWord 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param request
	 * @param @param response
	 * @param @param mobile
	 * @param @param passWord
	 * @param @param smsCode
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "保存修改密码",  response = BaseApiResult.class, notes = "修改密码")
	@RequestMapping(value="/changePWord")
	public BaseApiResult changePWord(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "mobile", value = "手机号")@RequestParam(value = "mobile", required = true)String mobile,
			@ApiParam(required = true, name = "passWord", value = "密码")@RequestParam(value = "passWord", required = true)String passWord,
			@ApiParam(required = true, name = "smsCode", value = "验证码")@RequestParam(value = "smsCode", required = true)String smsCode){
		
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				UserCenterResult checkResult = userRegisterService.checkSMSCode(mobile, smsCode, BizTypeEnum.SmsFindPassword);
				if( checkResult.isSuccess()){
					UserCenterResult userCenterResult = userRegisterCheckService.checkMobileOrEmailExist(mobile, null);
					if( userCenterResult.isSuccess()){
						result.setMsg("手机号未注册");
						result.setRes(0);
					}else{
						if( passWord.trim().matches(regpw)){
							userService.updatePwdByMobile( mobile, passWord);
							result.setMsg("密码修改成功");
						}else{
							result.setMsg("密码不符合规则，请修改");
							result.setRes(0);
						}
					}
				}else{
					result.setMsg(checkResult.getMsg());
					result.setRes(0);
				}
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	

	/** 
	 * @Title: serchCompany 
	 * @Description: TODO(企业关键字模糊查询，返回结果最多10条) 
	 * @param @param request
	 * @param @param response
	 * @param @param companyName
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 *//* 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "查询企业名称",  response = BaseApiResult.class, notes = "查询企业名称")
	@RequestMapping(value="/serchCompany")
	public BaseApiResult serchCompany(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "companyName", value = "企业名")
			@RequestParam(value = "companyName", required = true)String companyName){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(companyName)){
			CommonResult commonResult = companyService.selectByName( companyName);
			if( commonResult.hasData()){
				List<Company> data = commonResult.getData();
				result.setMsg("查询成功");
				result.setData(data);
			}else{
				result.setMsg("暂无相关数据");
				result.setRes(0);
			}
		}else{
			result.setMsg("请输入关键字");
			result.setRes(0);
		}
		
		return result;
	}*/
	
	/**
	 * 
	  * @method: sendFindPasswordAuthCode
	  * @author: ybr
	  * @date: 2015年8月19日
	  * @Description: 找回密码短信校验码发送接口
	  * @param request
	  * @param response
	  * @param mobile
	  * @return BaseApiResult
	  *
	 */
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "找回密码短信校验码发送",  response = BaseApiResult.class, notes = "找回密码短信校验码发送")
	@RequestMapping(value="/sendFindPasswordAuthCode")
	public BaseApiResult sendFindPasswordAuthCode(HttpServletRequest request,HttpServletResponse response ,
			@ApiParam(required = true, name = "mobile", value = "手机号")
			@RequestParam(value = "mobile", required = true)String mobile){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				BizTypeEnum type = BizTypeEnum.SmsFindPassword;
				int codeType = SendSMSTypeEnum.FIND_PASSWORD.getIndex();
				UserCenterResult sendResult = userRegisterService.sendSMSCode(mobile, type.name(), type, codeType);
				if(sendResult.isSuccess()){
					result.setMsg("短信发送成功");
					return result;
				}
				result.setMsg(sendResult.getMsg());
				result.setRes(0);
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	
	/**
	 * 根据注册用户基本信息
	 * @param request
	 * @param response
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value="/saveUserInfoApi")
	public BaseApiResult saveUserInfoApi(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "phone", value = "用户手机号（必须传入参数）")@RequestParam(value = "phone", required = true)String phone,
			@ApiParam(required = false, name = "industryId", value = "行业类别ID")@RequestParam(value = "industryId", required = false)String industryId,
			@ApiParam(required = false, name = "industry", value = "行业类别名称")@RequestParam(value = "industry", required = false)String industry,
			@ApiParam(required = false, name = "org", value = "公司名称")@RequestParam(value = "org", required = false)String org,
			@ApiParam(required = false, name = "realname", value = "真实姓名")@RequestParam(value = "realname", required = false)String realname,
			@ApiParam(required = false, name = "position", value = "职务")@RequestParam(value = "position", required = false)String position,
			@ApiParam(required = false, name = "locationId", value = "地区ID")@RequestParam(value = "locationId", required = false)String locationId,
			@ApiParam(required = false, name = "locationName", value = "地区名称(针对iosGPS定位只能定位地区汉字无编码的情况，与locationId互斥)")@RequestParam(value = "locationName", required = false)String locationName,
			@ApiParam(required = false, name = "uemail", value = "uemail")@RequestParam(value = "uemail", required = false)String uemail,
			@ApiParam(required = false, name = "info", value = "个人说明")@RequestParam(value = "info", required = false)String info
			)throws IOException{
		BaseApiResult result= new BaseApiResult();
		result.setMsg("保存客户信息成功");
//		BaseUser baseUser = FrontLoginUtil.getCurrentUser();
//		baseUser = new BaseUser();
//		baseUser.setMobile("13638676664");
//		baseUser.setUid(1L);
		if(StringUtils.isBlank(phone)){
			result.setRes(0);
			result.setMsg("保存客户信息失败,用户电话号码不能为空");
			return result;
		}
		User user = loginUserService.findByLoginName(phone);
		if(null!=user){
		if(StringUtils.isNumeric(industryId) || StringUtils.isNotBlank(industry)|| StringUtils.isNotBlank(org) || StringUtils.isNotBlank(realname)|| StringUtils.isNotBlank(uemail)){
			if(StringUtils.isNumeric(industryId) && StringUtils.isNotBlank(industry)){
				user.setIndustry(industry);
				user.setIndustryId(Long.valueOf(industryId));
			}
	        
			if(StringUtils.isNotBlank(org)){
				user.setOrg(org);
			}
			
			if(StringUtils.isNotBlank(realname)){
				user.setRealname(realname);
			}
			if(StringUtils.isNotBlank(uemail)){
				user.setUemail(uemail);;
			}
			try {
				userService.update(user);
				result.setRes(1);
			} catch (Exception e) {
				result.setRes(0);
				result.setMsg("保存客户信息失败");
			}
		}
		if(StringUtils.isNotBlank(position)|| StringUtils.isNotBlank(locationId) || StringUtils.isNotBlank(info) || StringUtils.isNotBlank(locationName)){
			UserInfoVO vo = new UserInfoVO();
			vo.setUserId(user.getUid().toString());
			Map<String,String> map = new HashMap<String, String>();
			if(StringUtils.isNotBlank(locationId)){
				map.put(UserInfoName.LOCATION.name(), locationId);
			}else if(StringUtils.isNotBlank(locationName)){
				//根据名称查询区域ID
				CityInfo infoCity = cityInfoService.findByCityName(locationName);
				if(null!=infoCity && !"".equals(infoCity)){
					map.put(UserInfoName.LOCATION.name(), infoCity.getPostcode());
				}else{
					result.setRes(0);
					result.setMsg("用户所在地区保存失败，请手动选择");
					return result;
				}
				
				
			}
			
			if(StringUtils.isNotBlank(position)){
				map.put(UserInfoName.POSITION.name(), position);
			}
			
			if(StringUtils.isNotBlank(info)){
				map.put(UserInfoName.INFO.name(), info);
			}
			
			
			vo.setInfoMap(map);
			try {
				userInfoService.batchSave(vo);
				result.setRes(1);
				result.setMsg("保存信息成功");
			} catch (Exception e) {
				result.setRes(0);
				result.setMsg("保存客户信息失败");
			}
		}

		}else{
			result.setRes(0);
			result.setMsg("此客户未注册");	
		}
		
		return result;	
	}
}
